<?php
chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir("../");
$path3 = getcwd();
chdir(dirname(__FILE__));
#debug($path3 , $path2);
include_once $path3."/lib/core.class.php";

// ----------------------------------------------------------------------------------
// --- [ Enable Ajax ] ---------------------------------------------------
// ----------------------------------------------------------------------------------


class Discounts extends IPlugin 
{
    var $color;
    var $view_type_discount;
    
    function Discounts($parent = null)
    {
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__) . "/tpl";
        $this->color = "blue";
        $this->view_type_discount = 0;
    }
    
    function getPluginTag() { return "discounts"; }
    function getPluginName() { return "Discounts Plugin"; }
    function getPluginVersion() { return "1.0.0"; }
    
    function getProperty($p = null)
    {
        if(null == $p)
        {
            return array("MenuTitle", "MenuBlockTitle");
        }
        $result = "";
        switch ($p)
        {
            case "MenuBlockTitle": { return "Discounts"; } break;
            case "MenuTitle" : { return "Discounts"; } break;
        };
        return $result;
    }
    
    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------

    function doAction($params)
    {
        if(null != ($result = IPlugin::doAction($params)))
        {
            return $result;
        }

        $core = getCoreInstance();
        $db = $core->getProperty("db");
        $framework = $core->getProperty("framework");
        $render = $framework->smarty;

        switch ($_GET["event"]) 
        {
            case "delete" :
                    $this->view_type_discount = $db->getOne("select id_type from discount where id_discount = " . $_GET['id']);
                    $db->Exec("delete from discount where id_discount = " . $_GET['id']);
                    break;
            default: break;
        }


        $action = ($_POST['event'] == "add") ? "insert" : "update";
        switch ($_POST['action'])
        {
            case "discount_coupon" : 
                    {
                        $items_list = "";
                        if (isset($_POST['all_items']))
                            $items_list = "0";
                        else
                        {
                            foreach ($_POST['selected_items_list'] as $item)
                                $items_list .= ($items_list == "" ? "" : ",") . $item;
                        }
                        
                        $type_pay = $_POST['disc_am'][0] == "0" ? "$" : "%";
                        $value_discount = $_POST['discount_amount'];
                        
                        if ("insert" == $action)
                            $sql_query = "insert into discount (id_type, title, code_coupon, group_items, date_begin, date_ending, value_discount, type_payment, type_form, description) " .
                                "values ({$_POST[discount_type]}, '" . str2db($_POST['discount_title']) . "', '" . str2db($_POST['discount_code']) . "'" .
                                ", '{$items_list}', '" . date("Y-m-d", strtotime($_POST['discount_begin'])) . "', '" . date("Y-m-d", strtotime($_POST['discount_ending'])) . "'" . 
                                ", {$value_discount}, '{$type_pay}', 'coupon', '" . str2db($_POST['description']) . "')";
                        else
                            $sql_query = "update discount set group_items = '{$items_list}', date_begin = '" . date("Y-m-d", strtotime($_POST['discount_begin'])) . "'" .
                                    ", date_ending = '" . date("Y-m-d", strtotime($_POST['discount_ending'])) . "', type_payment = '{$type_pay}'" .
                                    ", value_discount = {$value_discount}, code_coupon = '" . str2db($_POST['discount_code']) . "'" . 
                                    ", title = '" . str2db($_POST['discount_title']) . "', id_type = {$_POST[discount_type]}" .
                                    ", description = '" . str2db($_POST['description']) . "' where id_discount = {$_POST[id_discount]}";
                         $db->Exec($sql_query);
                         $this->view_type_discount = $_POST['discount_type'];
                         break;
                    };

            case "discount_dates" : 
                    {
                        $items_list = "";
                        if (isset($_POST['all_items']))
                            $items_list = "0";
                        else
                        {
                            foreach ($_POST['selected_items_list'] as $item)
                                $items_list .= ($items_list == "" ? "" : ",") . $item;
                        }
                        
                        $type_pay = $_POST['disc_am'][0] == "0" ? "$" : "%";
                        $value_discount = $_POST['discount_amount'];
                        
                        if ("insert" == $action)
                            $sql_query = "insert into discount (id_type, group_items, date_begin, date_ending, type_payment, value_discount, title, type_form, description) " .
                                "values ({$_POST[discount_type]}, '{$items_list}', '" . date("Y-m-d", strtotime($_POST['discount_begin'])) . "'" .
                                ", '" . date("Y-m-d", strtotime($_POST['discount_ending'])) . "', '{$type_pay}', {$value_discount}" .
                                ", '" . str2db($_POST['discount_title']) . "', 'date', '" . str2db($_POST['description']) . "')";
                         else
                            $sql_query = "update discount set group_items = '{$items_list}', date_begin = '" . date("Y-m-d", strtotime($_POST['discount_begin'])) . "'" .
                                    ", date_ending = '" . date("Y-m-d", strtotime($_POST['discount_ending'])) . "', type_payment = '{$type_pay}'" .
                                    ", value_discount = {$value_discount}, title = '" . str2db($_POST['discount_title']) . "', id_type = {$_POST[discount_type]}" .
                                    ", description = '" . str2db($_POST['description']) . "' where id_discount = {$_POST[id_discount]}";
                         
                         $db->Exec($sql_query);
                         $this->view_type_discount = $_POST['discount_type'];
                         break;
                    }


            case "discount_pr_count" : 
                    {
                        $items_list = "";
                        if (isset($_POST['all_items']))
                            $items_list = "0";
                        else
                        {
                            foreach ($_POST['selected_items_list'] as $item)
                                $items_list .= ($items_list == "" ? "" : ",") . $item;
                        }
                        
                        $type_pay = $_POST['disc_am'][0] == "0" ? "$" : "%";
                        $value_discount = $_POST['discount_amount'];
                        
                        if ("insert" == $action)
                            $sql_query = "insert into discount (id_type, group_items, date_begin, date_ending, amount_buying, type_amount_buying, type_payment, value_discount, type_form, description, title) " .
                                "values ({$_POST[discount_type]}, '{$items_list}', '" . date("Y-m-d", strtotime($_POST['discount_begin'])) . "'" .
                                ", '" . date("Y-m-d", strtotime($_POST['discount_ending'])) . "', {$_POST['discount_pr_count']}, '" . 
                                ($_POST['p_c'][0] == 1 ? "a" : "$") .  "',  '{$type_pay}', {$value_discount}, '" . str2db("price/count discount") . 
                                "', '" . str2db($_POST['description']) . "', '" . str2db($_POST['discount_title']) . "')";
                        else
                            $sql_query = "update discount set group_items = '{$items_list}', date_begin = '" . date("Y-m-d", strtotime($_POST['discount_begin'])) . "'" .
                                ", date_ending = '" . date("Y-m-d", strtotime($_POST['discount_ending'])) . "', amount_buying = {$_POST['discount_pr_count']}" .
                                ", type_amount_buying = '" . ($_POST['p_c'][0] == 1 ? "a" : "$") . "', type_payment = '{$type_pay}'" .
                                ", value_discount = {$value_discount}, id_type = {$_POST[discount_type]}, title = '" . str2db($_POST['discount_title']) . "'" .
                                ", description = '" . str2db($_POST['description']) . "' where  id_discount = {$_POST[id_discount]}";
                        
                         
                         $db->Exec($sql_query);
                         $this->view_type_discount = $_POST['discount_type'];
                         break;
                    }

            default : break;
        }
  
    }



    // ----------------------------------------------------------------------------------
    // --- [ Render pages ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------

    function Render($params)
    {
        global $_G;
        if(null != ($result = IPlugin::Render($params)))
        {
            return $result;
        }
        
        $core = &getCoreInstance();
        $db = $core->getProperty("db");
        $framework = $core->getProperty("framework");
        $render = $framework->smarty;
        $render->assign("baseurl", "?".$this->getURL()."&page=".$_G["page"]);

        $page = "";

        switch ($_G["page"]) 
        {
            case "edit" : 
                $this->renderDiscountEdit($render, $db, $core);
                $page = "discount_edit.tpl.php";
                 break;
            
            case "add" : 
                $this->renderDiscountAdd($render, $db, $core);
                $page = "discount_edit.tpl.php";
                 break;

            default: 
                $this->renderDiscount($render, $db, $core);
                $page = "discount_view.tpl.php";
                 break;
        }

        return $render->fetch("file:" . $this->tplfolder . "/" . $page);
    }
    
    // ----------------------------------------------------------------------------------
    // --- [ Render Discount View Page ] ---------------------------------------------------
    // ----------------------------------------------------------------------------------
    function cb_rndDis($data)
    {
        $dt = array(
                array($data["id_discount"], "align=\"center\""),
                array($data["title"], ""),
                array(date("m/d/Y h:i A", strtotime($data["date_begin"])), ""),
                array(date("m/d/Y h:i A", strtotime($data["date_ending"])), ""),
                array($data["type_payment"] == "$" ? $data["type_payment"] . $data["value_discount"] : $data["value_discount"] . $data["type_payment"], ""),
                array($data["description"], ""),
                array("<a href=\"?".$this->getURL()."&page=edit&id={$data[id_discount]}\">edit</a>&nbsp;&nbsp;&nbsp;<a href=\"?".$this->getURL()."&event=delete&id={$data[id_discount]}\">delete</a>","align=\"center\""),
                );
        return $dt;
    }


    function renderDiscount(&$render, &$db, &$core)
    {
      
        $pg = &$core->getSnippet("paginator");

        $id_type = isset($_POST['type_id']) ? $_POST['type_id'] : $this->view_type_discount;
        
        $params = array(
                    "cb_class" => &$this,
                    "cb_func" => cb_rndDis,
                    "urlbase" => $this->getURL(),
                    "caption" => "Discounts list",
                    "emptymsg" => "<center>No discounts for selected type created yet</center>",
                    "header" => array("ID", "Discount Title", "Date Begin", "Date Ending", "Discount Amount", "Discount Description", "Actions"),
                    "items" => "",
                    "source" => "sql", // -- sql, array
                    "sql_items" => "select id_discount, title, date_begin, date_ending, value_discount, type_payment, description  from discount where id_type = {$id_type} order by title asc",
                    "sql_count" => "select count(*) from discount where id_type = {$id_type}",
                    "ippg" => 15, // -- items per page
                    "nppv" => 5, // -- number pages per view
                    );

        $HTML = $pg->Render($params);
        $render->assign("discounts", $HTML);

        // Get list types discounts
        $arr_types = $db->getAll("select id_type, title from discount_type order by title asc");
        $render->assign("types_discounts", $arr_types);
        $render->assign("cur_type", $id_type);
        $render->assign("url_location", "?".$this->getURL());
     }

    // ----------------------------------------------------------------------------------
    // --- [ Render Discount Edit Page ] ---------------------------------------------------
    // ----------------------------------------------------------------------------------

    function renderDiscountEdit(&$render, &$db, &$core)
    {
        // Get data about dsicount
        $sql = "select id_discount, id_type, title, code_coupon, group_items, date_begin, date_ending, amount_buying, type_amount_buying, value_discount";
        $sql .= ", type_payment, description, type_form";
        $sql .= " from discount";
        $sql .= " where id_discount = " . $_GET['id'];
        $arr_data = ArrayDb2Str($db->getAll($sql));

        $render->assign("data", $arr_data[0]);
        //print_r($arr_data[0]);
        
        // Flag edit or create. If edit = 1 - edit
        $render->assign("edit", 1);
        $render->assign("action_url", "?".$this->getURL());

        // data about table with products
        $str_catalogid = $core->config['discounts']['catalogid'];
        $str_parent_id = $core->config['discounts']['parent_id'];
        $str_title = $core->config['discounts']['title'];
        $str_table = $core->config['discounts']['product_table'];
        $str_iscategory = $core->config['discounts']['iscategory'];
        $str_iscategory_true = $core->config['discounts']['iscategoryTrue'];
        $str_iscategory_false = $core->config['discounts']['iscategoryFalse'];
        $str_itemnumber = $core->config['discounts']['itemnumber'];

        // Get list catalogs from table with products
        if ("" != $str_iscategory)
        {
            $arr_catalogs = $db->getAll("select {$str_catalogid} as catalogid, {$str_title} as title from {$str_table} where {$str_iscategory} = '{$str_iscategory_true}' order by title asc");
            $render->assign("arr_catalogs", ArrayDb2Str($arr_catalogs));
        }

        // Get list products in root from table with products
        $sql = "select " . ("" == $str_itemnumber ? "" : $str_itemnumber . ", ");
        $parent_id = ("" == $str_parent_id) ? "" : " and " . $str_parent_id . " = 0";
        $iscategory = ("" == $str_iscategory) ? "" : " and " . $str_iscategory . " = '{$str_iscategory_false}'";
        $sql .= "{$str_catalogid} as catalogid, {$str_title} as title from {$str_table} where 1 = 1 {$iscategory}";
        $sql .= $parent_id . " order by title asc";
        $arr_root_items = $db->getAll($sql, 2);
        $render->assign("arr_root_items", ArrayDb2Str($arr_root_items));
        
        // Get list products selected for discount from table with products
        $sql = "select " . ("" == $str_itemnumber ? "" : $str_itemnumber . ", ");
        $arr_data[0]['group_items'] = "" == $arr_data[0]['group_items'] ? '0' : $arr_data[0]['group_items'];
        $sql .= "{$str_catalogid} as catalogid, {$str_title} as title from {$str_table} where {$str_catalogid} in ({$arr_data[0][group_items]})";
        $arr_items = $db->getAll($sql, 2);
        $render->assign("arr_items", ArrayDb2Str($arr_items));
        
        
        $render->assign("http_root", $core->config["http_root"]);
        
        // Get list types discounts
        $arr_types = $db->getAll("select id_type, title from discount_type order by title asc");
        $render->assign("types_discounts", $arr_types);
    }

    // ----------------------------------------------------------------------------------
    // --- [ Render Discount Edit Page ] ---------------------------------------------------
    // ----------------------------------------------------------------------------------

    function renderDiscountAdd(&$render, &$db, &$core)
    {
        // Flag edit or create. If edit = 1 - edit
        $render->assign("edit", 0);
        $render->assign("action_url", "?".$this->getURL());

        // data about table with products
        $str_catalogid = $core->config['discounts']['catalogid'];
        $str_parent_id = $core->config['discounts']['parent_id'];
        $str_title = $core->config['discounts']['title'];
        $str_table = $core->config['discounts']['product_table'];
        $str_iscategory = $core->config['discounts']['iscategory'];
        $str_iscategory_true = $core->config['discounts']['iscategoryTrue'];
        $str_iscategory_false = $core->config['discounts']['iscategoryFalse'];
        $str_itemnumber = $core->config['discounts']['itemnumber'];

        // Get list catalogs from table with products
        if ("" != $str_iscategory)
        {
            $arr_catalogs = $db->getAll("select {$str_catalogid} as catalogid, {$str_title} as title from {$str_table} where {$str_iscategory} = '{$str_iscategory_true}' order by title asc");
            $render->assign("arr_catalogs", ArrayDb2Str($arr_catalogs));
        }


        // Get list products in root from table with products
        $sql = "select " . ("" == $str_itemnumber ? "" : $str_itemnumber . ", ");
        $parent_id = ("" == $str_parent_id) ? "" : " and " . $str_parent_id . " = 0";
        $iscategory = ("" == $str_iscategory) ? "" : " and " . $str_iscategory . " = '{$str_iscategory_false}'";
        $sql .= "{$str_catalogid} as catalogid, {$str_title} as title from {$str_table} where 1 = 1 {$iscategory}";
        $sql .= $parent_id . " order by title asc";
        $arr_root_items = $db->getAll($sql, 2);
        $render->assign("arr_root_items", ArrayDb2Str($arr_root_items));
    
        $render->assign("http_root", $core->config["http_root"]);
        
        // Get list types discounts
        $arr_types = $db->getAll("select id_type, title from discount_type order by title asc");
        $render->assign("types_discounts", $arr_types);
        
        // Set flag on form
        $render->assign("data", array('type_form' => 'coupon'));
    }

};


?>